﻿using Core.SimpleTemp.Api.Swagger;
using Core.SimpleTemp.Application;
using Core.SimpleTemp.Common;
using Core.SimpleTemp.Common.Authorization;
using Core.SimpleTemp.Common.Filters;
using Core.SimpleTemp.Repositories.Internal;
using Core.Toolkit.AutoMapperExtend.DataDictionary;
using Core.Toolkit.Core.Application;
using Core.Toolkit.ServiceCollectionExtensions;
using Core.Toolkit.Startup;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NLog.Web;
using System;
using System.Collections.Generic;
using UEditorNetCore;

#pragma warning disable CS1591
namespace Core.SimpleTemp.Mvc
{
    public class Startup
    {
        private const string WEBAPP_OPTIONS = "WebAppOptions";
        public IConfiguration Configuration { get; }
        private readonly ILogger _logger;
        private readonly WebAppOptions _webAppOptions;

        public Startup(IConfiguration configuration, ILogger<Startup> logger)
        {
            Configuration = configuration;
            _webAppOptions = Configuration.GetSection(WEBAPP_OPTIONS).Get<WebAppOptions>();
            _logger = logger;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<CoreDBContext>(options =>
            {
                options.UseRemoveForeignKeyService();
                //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), sqlOptions => sqlOptions.UseRowNumberForPaging());
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
                //options.UseNpgsql(_configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddTransient<IGetFunctionCode, SysLoginService>();//自定义授权
            services.AddToolkit(_webAppOptions, Configuration, _logger);
            services.AddSwaggerService();
            services.AddUEditorService();
            services.AddMvc(options =>
            {
                //自定义全局异常过滤器
                options.Filters.Add<HttpGlobalExceptionFilter>();
            }).AddJsonOptions(options =>
            {
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime, ILoggerFactory loggerFactory)
        {
            appLifetime.ApplicationStarted.Register(OnStarted, app);
            #region Nlog
            if (System.IO.File.Exists(System.IO.Path.Combine(env.ContentRootPath, $"Nlog.{ env.EnvironmentName}.config")))
                env.ConfigureNLog($"Nlog.{env.EnvironmentName}.config");
            else
                env.ConfigureNLog($"Nlog.config");
            #endregion
            if (!string.IsNullOrEmpty(_webAppOptions.DefaultPage))
            {
                DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
                defaultFilesOptions.DefaultFileNames.Clear();
                defaultFilesOptions.DefaultFileNames.Add(_webAppOptions.DefaultPage);
                app.UseDefaultFiles(defaultFilesOptions);
            }
            app.UseToolkit(env, appLifetime, _webAppOptions);
            app.UseSwagger(env);
            app.UseAuthentication();
            app.UseMvcWithDefaultRoute();
        }

        /// <summary>
        /// 应用服务器启动时调用
        /// </summary>
        /// <param name="app"></param>
        private void OnStarted(object app)
        {
            var applicationBuilder = (IApplicationBuilder)app;
            var dataDicPool = applicationBuilder.ApplicationServices.GetService<IDataDicPool>();
            //字典热更新初始数据加载
            var _serviceProvider = applicationBuilder.ApplicationServices.GetService<IServiceProvider>();
            using (var scope = _serviceProvider.CreateScope())
            {
                var services = scope.ServiceProvider;
                var concurrentDataDicProvider = services.GetRequiredService<IEnumerable<IConcurrentDataDicProvider>>();
                ConcurrentDataDicPool.Initialization(concurrentDataDicProvider);
            }
            CoreMapper.Initialize(dataDicPool);
        }
    }
}
